<?php

namespace App\Http\Controllers\Admin;

use App\Exports\HousingsCommentExport;
use App\Http\Filters\HousingsCommentFilter;
use App\Models\AppUser;
use App\Models\Housings;
use App\Models\HousingsComment;
use App\Http\Requests\HousingsCommentRequest;
use App\Http\Resources\HousingsCommentResource;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class HousingsCommentController extends Controller
{
    public function index(HousingsCommentFilter $filter)
    {
        $housingsComments = HousingsComment::query()
            ->with('housingsorder','user','housings')
            ->filter($filter)
            ->paginate();

        return $this->ok(HousingsCommentResource::collection($housingsComments));
    }

    public function create()
    {
        return $this->ok();
    }

    public function store(HousingsCommentRequest $request)
    {
        $inputs = $request->validated();
        $housingsComment = HousingsComment::create($inputs);

        return $this->created(HousingsCommentResource::make($housingsComment));
    }

    public function edit(Request $request, HousingsComment $housingsComment,$id)
    {
        $housingsComment = HousingsComment::findOrFail($id);
        return $this->ok(HousingsCommentResource::make($housingsComment)->additional($this->formData($housingsComment)));
    }

    protected function formData($report)
    {

        $housings = Housings::where("id",$report['housings_id'])->select('housings_num','id','hou_address')
            ->orderByDesc('id')
            ->first();
       $user= AppUser::where("id",$report['user_id'])->select('id','real_name')
            ->orderByDesc('id')
            ->first();
        return compact('housings','user');
    }

    public function update(HousingsCommentRequest $request, HousingsComment $housingsComment)
    {
        $inputs = $request->validated();
        $housingsComment->update($inputs);

        return $this->created(HousingsCommentResource::make($housingsComment));
    }

    public function destroy(HousingsComment $housingsComment)
    {
        $housingsComment->delete();
        return $this->noContent();
    }

    public function export(Request $request)
    {

        $filters = $request->only([
            'ids',
            // ... 其他可能的过滤条件
        ]);
        return Excel::download(new HousingsCommentExport($filters), '入住评论.xlsx');
    }
}
